using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CtrlVolume : MonoBehaviour
{

    [Header("是否bgm控制器")]
    public bool is_bgm_controller = true;

    Slider volumeSlider;

    AudioSource bgm_audio_source_comp;

    private AppFileTools.FileObject volume_file_obj;

    private void Awake()
    {
        volume_file_obj = new AppFileTools.FileObject(file_name: "volume.json", dir_name:"archives", create_if_not_exists: true);
        // volumeSlider = GetComponent<Slider>() || GetComponentInChildren<Slider>();
        volumeSlider = GetComponent<Slider>();

        // var bgm_audio_clip_obj = BdTools.get_game_object_by_path("/scripts/BackgroundMusic");

        if (is_bgm_controller)
        {
            var bgm_obj = GameObject.Find("/scripts/BackgroundMusic");
            if (bgm_obj)
                bgm_audio_source_comp = bgm_obj.GetComponent<AudioSource>();
            BdUtils.assert(bgm_audio_source_comp, "bgm_audio_clip_comp为空?");
        }
        BdUtils.log(" === persistent path:", BdUtils.persistentDataPath);
        // gameObject.SetActive(false);

    }

    private string audio_key
    {
        get
        {
            string key = is_bgm_controller ? "bgm_volume" : "base_volume";
            return key;
        }
    }
    
    private void set_game_memory_value(float value = BdUtils.DEFAULT_FLOAT)
    {
        if (Mathf.Approximately(value, BdUtils.DEFAULT_FLOAT))
        {
            value = audio_value;
        }
        
        if (is_bgm_controller)
            BdTools.Values.bgm_volume = value;
        else
            BdTools.Values.base_volume = value;
    }

    private float audio_value
    {
        get
        {
            float value = volume_file_obj.content_dc.TryGetValue(audio_key, out object _value) ? BdUtils.conv_to_float(_value) : 0.5f;
            // set_game_memory_value(value);
            return value;
        }
        set
        {
            volume_file_obj.content_dc[audio_key] = value;
            set_game_memory_value(value);
            volume_file_obj.save();
        }
    }

    private void OnEnable()
    {
        float value = audio_value;
        if (!Mathf.Approximately(value, volumeSlider.value)) 
        {
            volumeSlider.value = value;

            // BaseInfoManager.instance.set_game_volume(value, is_bgm_controller);
            // public string values_file_path = BdUtils.join(BdUtils.persistant_data_dir_path, BdTools.Values.values_file_name);

            // BdTools.FileTools.instance.set_game_volume(value, is_bgm_controller);
        }
    }
    
    private void Update()
    {
        float value = audio_value;

        if (!Mathf.Approximately(value, volumeSlider.value)) 
        {
            audio_value = volumeSlider.value;
        }
    }
}
